// HTTP请求基础服务

// 基础域名
const BASE_URL = 'https://okeydo.fourcats.online';

// API密钥
const API_KEY = 'c4608807-6562-41ac-9574-381250f2c41b';

// 请求方法封装
export const request = <T>(options: {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: Record<string, string>;
  needToken?: boolean; // 是否需要token
}): Promise<T> => {
      return new Promise((resolve, reject) => {
      // 获取本地存储的token
      const token = options.needToken !== false ? wx.getStorageSync('token') : null;

      wx.request({
        url: BASE_URL + options.url,
        method: options.method || 'GET',
        data: options.data,
        header: {
          'content-type': 'application/json',
          'Authorization': token ? `Bearer ${token}` : '',
          'X-API-KEY': API_KEY,
          ...options.header
        },
      success: (res: any) => {
        if (res.statusCode === 200) {
          // 检查业务状态码
          console.log('请求结果', res)
          if ((res && res.data && res.data.code === 0) || (res && res.data && res.data.code === 200)) {
            resolve(res.data as T);
          } else {
            wx.showToast({
              title: (res.data && res.data.message) || '请求失败',
              icon: 'none'
            });
            reject(res.data || res);
          }
        } else if (res.statusCode === 401) {
          // token失效，不清除refreshToken，让authManager处理刷新
          console.log('401错误，不清除refreshToken，让authManager处理')
          reject(res);
        } else {
          wx.showToast({
            title: (res.data && res.data.message) || '请求失败',
            icon: 'none'
          });
          reject(res);
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络异常',
          icon: 'none'
        });
        reject(err);
      }
    });
  });
};

// 导出请求方法
export const http = {
  get: <T>(url: string, data?: any, header?: Record<string, string>, needToken?: boolean) => {
    return request<T>({ url, method: 'GET', data, header, needToken });
  },
  post: <T>(url: string, data?: any, header?: Record<string, string>, needToken?: boolean) => {
    return request<T>({ url, method: 'POST', data, header, needToken });
  },
  put: <T>(url: string, data?: any, header?: Record<string, string>, needToken?: boolean) => {
    return request<T>({ url, method: 'PUT', data, header, needToken });
  },
  delete: <T>(url: string, data?: any, header?: Record<string, string>, needToken?: boolean) => {
    return request<T>({ url, method: 'DELETE', data, header, needToken });
  }
};